<template>
  <van-dialog
    v-model="payShow"
    :title="title"
    show-cancel-button
    confirm-button-text="去支付"
    cancel-button-text="取消支付"
    @confirm="handleDoPay"
    @cancel="handleCancel"
  >
    <div class="pay-container">
      <div class="money-container">
        支付金额：<span>￥{{ orderHeader.grandTotal }}</span>
      </div>
      <div class="desc-container">交易订单：{{ orderHeader.id }}</div>
      <div class="desc-container">购买物品：{{ orderHeader.orderName }}</div>
      <div class="payMethod-container">
        <van-radio-group v-model="payMethod" direction="horizontal">
          <van-radio name="zfb">支付宝支付 </van-radio>
          <van-radio name="wx_v3">微信支付</van-radio>
        </van-radio-group>
      </div>
    </div>
  </van-dialog>
</template>
<script>
import wxPubAuth from '@/utils/WxPubAuth'
var jweixin = require('jweixin-module')
export default {
  props: {
    title: {
      type: String,
      default: '订单支付'
    }
  },
  data() {
    return {
      payShow: false,
      orderId: null,
      orderHeader: {},
      payMethod: 'zfb',
      qrcodeLoading: false,
      orderStatusInterval: null,
      wxPrePay: {}
    }
  },

  created() {
    if (this.T.isWeiXin()) {
      var { openId, orderId } = this.$route.query
      if (openId && orderId) {
        window.location.href = this.gelDelURL()
        this.handleDoWxPay(orderId, openId)
      }
    }
  },
  mounted() {
  },
  destroyed() {
    if (this.orderStatusInterval) {
      clearInterval(this.orderStatusInterval)
    }
  },
  methods: {
    init(orderId) {
      if (this.T.isWeiXin()) {
        wxPubAuth.doWxPubAuth('?orderId=' + orderId)
      } else {
        this.payShow = true
        this.orderId = orderId
        this.payMethod = 'zfb'
        this.qrcodeLoading = false
        this.fetchOrder()
      }
    },
    fetchOrder() {
      this.$store.dispatch('businessOrderHeaderGetById', this.orderId).then((res) => {
        this.orderHeader = res
      }).catch((_) => {})
    },
    handleCancel() {

    },
    handleDoPay() {
      this.$store.dispatch('h5Pay', {
        orderNo: this.orderId,
        payMethod: this.payMethod,
        returnUrl: window.g.payResultUrl
      }).then(res => {
        console.log(res)
        var div = document.createElement('div')
        div.innerHTML = res
        document.body.appendChild(div)
        document.forms[0].submit()
      }).catch((_) => {
        this.payShow = true
      })
    },
    orderStatusByOrderId() {
      this.$store.dispatch('orderStatusByOrderId', { orderId: this.orderId, loading: false }).then((res) => {
        if (res === 2) {
          if (this.orderStatusInterval) {
            clearInterval(this.orderStatusInterval)
          }
          this.payShow = false
          this.msgSuccess('支付成功!')
          this.$emit('payNotify', true)
        }
      }).catch((_) => {})
    },
    handlePayClose() {
      this.payShow = false
      this.clearInterval()
    },
    clearInterval() {
      if (this.orderStatusInterval) {
        clearInterval(this.orderStatusInterval)
      }
    },
    bindWeiXin(orderId) {
      window.location.href = window.g.wxAuthUrl + '?callback=' + encodeURIComponent(window.location.href) + '?orderId=' + orderId
    },
    handleDoWxPay(orderId, openId) {
      this.$store.dispatch('doPrepay', {
        orderNo: orderId,
        openId: openId,
        tradeType: 'OFFICIAL_ACCOUNT',
        payMethod: 'wx_v3'
      }).then(res => {
        this.payData = {
          timeStamp: res.timeStamp,
          nonceStr: res.nonceStr,
          package: res.packageVal,
          signType: res.signType,
          paySign: res.paySign,
          appId: res.appId
        }
        this.wxConfig()
      }).catch(() => {
      })
    },
    wxConfig() {
      jweixin.config({
        debug: false, // 测试开一下
        appId: this.payData.appId, // 必填，公众号的唯一标识
        timestamp: this.payData.timeStamp, // 必填，生成签名的时间戳
        nonceStr: this.payData.nonceStr, // 必填，生成签名的随机串
        signature: this.payData.paySign, // 必填，签名
        jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表
      })
      this.beforePay()
    },
    beforePay() {
      const self = this
      jweixin.ready(function() {
        jweixin.checkJsApi({
          jsApiList: ['chooseWXPay'],
          success: function(res) {
            self.choosePay()
          }
        })
      })
      jweixin.error(function(res) {
        console.log(res, 'error')
      })
    },
    choosePay() {
      jweixin.chooseWXPay({
        timestamp: this.payData.timeStamp,
        nonceStr: this.payData.nonceStr,
        package: this.payData.package,
        signType: this.payData.signType,
        paySign: this.payData.paySign,
        success: (res) => {
          this.msgSuccess('支付成功!')
          this.$emit('payNotify', true)
        }
      })
    },
    gelDelURL() {
      return window.location.href.substring(0, window.location.href.indexOf('?'))
    }
  }
}
</script>
  <style lang="scss" scoped>
  .pay-container{
    background-color: #fff;
    text-align: center;
    font-size: 14px;
    height: 100%;
    .money-container{
      margin-bottom: 10px;
      span{
        font-size: 20px;
        font-weight: bolder;
        color: #ba9411;
      }
    }
    .desc-container{
      margin-bottom: 10px;
    }
    .payMethod-container{
      margin-top: 15px;
      margin-bottom: 15px;
      justify-content: center;
      display: flex;
    }
  }
  </style>
